package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.stream.Collectors;

/**
 * @Author: wenjingyuan
 * @Date: 2023/03/28/21:23
 * @Description:阅读量+1
 */
@WebServlet("/addrcount")
public class AddReadCountServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg="未知错误！";
        int data=0;
        //1.得到前端参数进行校验
        String aidStr=req.getParameter("aid");
        if(!StrUtil.isBlank(aidStr)){
            //2.将访问量+1，得到执行的结果
            int aid=Integer.valueOf(aidStr);
            if(aid>0){
            Connection connection= DBUtils.getConnection();
            String sql="update article set readcount=readcount+1 where aid=?";
            PreparedStatement statement=connection.prepareStatement(sql);
            statement.setInt(1,aid);
            data=statement.executeUpdate();
            msg="成功";
            DBUtils.close(null,statement,connection);
            }else{
                msg="参数错误";
            }
        }else{
            msg="参数错误";
        }
        //3.将结果返回给前端
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
